package com.demo.logging.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.common.pojo.dto.OperationLogsDTO;
import com.demo.logging.mapper.OperationLogsMapper;
import com.demo.logging.pojo.dto.PageQueryDTO;
import com.demo.logging.pojo.entity.OperationLogs;
import com.demo.logging.result.PageResult;
import com.demo.logging.result.Result;
import com.demo.logging.service.IOperationLogsService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


import static com.demo.common.constants.DateTimeFormat.DATE_TIME_FORMAT;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hxt
 * @since 2025-06-19
 */
@Service
public class OperationLogsServiceImpl extends ServiceImpl<OperationLogsMapper, OperationLogs> implements IOperationLogsService {

    @Override
    public void saveOperationLogs(OperationLogsDTO operationLogsDTO) {
        Integer count = lambdaQuery().eq(OperationLogs::getLogId, operationLogsDTO.getLogId())
                .count();
        if (count > 0) {
            return;
        }
        OperationLogs operationLogs = new OperationLogs();
        BeanUtil.copyProperties(operationLogsDTO, operationLogs);
        save(operationLogs);
    }

    @Override
    public Result<PageResult> pageQuery(PageQueryDTO pageQueryDTO) {
        //如果存在起止时间，解析起止时间
        LocalDateTime startTime = null;
        LocalDateTime endTime = null;
        if (StrUtil.isNotBlank(pageQueryDTO.getStartTime()) && StrUtil.isNotEmpty(pageQueryDTO.getEndTime())) {
            //解析起止时间
            startTime = LocalDateTime.parse(pageQueryDTO.getStartTime(), DateTimeFormatter.ofPattern(DATE_TIME_FORMAT));
            endTime = LocalDateTime.parse(pageQueryDTO.getEndTime(), DateTimeFormatter.ofPattern(DATE_TIME_FORMAT));
        }
        Page<OperationLogs> page = lambdaQuery()
                .eq(ObjectUtil.isNotNull(pageQueryDTO.getUserId()), OperationLogs::getUserId, pageQueryDTO.getUserId())
                .ge(ObjectUtil.isNotNull(startTime), OperationLogs::getCreateTime, startTime)
                .le(ObjectUtil.isNotNull(endTime), OperationLogs::getCreateTime, endTime)
                .orderByDesc(OperationLogs::getCreateTime)
                .page(new Page<>(pageQueryDTO.getPage(), pageQueryDTO.getPageSize()));
        PageResult pageResult = new PageResult(page.getTotal(), page.getRecords());
        return Result.success(pageResult);
    }
}
